import fitz
filename = "../demo.pdf"
# 读取文本
def readText(filename, page_number):
    doc = fitz.open(filename)
    print("number of pages: %i" % doc.pageCount)
    # print(doc.metadata)
    page = doc.loadPage(page_number)
    text = page.getText("text")
    print(text)

# 从pdf中提取图片, 不是将文档的某一页存成图片
def saveImageFromPdf (filename, startPage, endPage):
    pdf_document = fitz.open(filename)
    for current_page in range(startPage, endPage):
        for image in pdf_document.getPageImageList(current_page):
            xref = image[0]
            pix = fitz.Pixmap(pdf_document, xref)
            if pix.n < 5:  # this is GRAY or RGB
                pix.writePNG("page%s-%s.png" % (current_page, xref))
            else:  # CMYK: convert to RGB first
                pix1 = fitz.Pixmap(fitz.csRGB, pix)
                pix1.writePNG("page%s-%s.png" % (current_page, xref))
                pix1 = None
            pix = None

# saveImageFromPdf(filename, 0, 100)


# 全文搜索给定的文本
search_term = "OVERCURRENT"
def searchKeyWord(filename, key_word):
    pdf_document = fitz.open(filename)
    for current_page in range(len(pdf_document)):
        page = pdf_document.loadPage(current_page)
        result_page = page.searchFor(key_word)
        if (result_page):
            print(result_page)

        # if result_page:
        #     # print("%s found on page %i" % (search_term, current_page))
        #     result_page.showPDFpage()

searchKeyWord(filename, search_term)


# https://blog.csdn.net/democrat800/article/details/79241438

# search_term = "控制盘"
# pdf_document = fitz.open(filename)
# def searchKeyWord(filename, key_word):
#     pdf_document = fitz.open(filename)
#     for current_page in range(len(pdf_document)):
#         page = pdf_document.loadPage(current_page)
#         if page.searchFor(search_term):
#             # print("%s found on page %i" % (search_term, current_page))
#             print(page)
#


















